package info.jimao.newsdk.utilities;

import android.content.Context;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InvalidClassException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class FileCacheUtils {
    private Context context;
    private static FileCacheUtils fileCacheUtils;

    public synchronized static FileCacheUtils getInstance(Context context) {
        if (fileCacheUtils == null) {
            fileCacheUtils = new FileCacheUtils(context);
        }
        return fileCacheUtils;
    }

    private FileCacheUtils(Context context) {
        this.context = context;
    }

    public void saveDataCache(Serializable ser, String cacheFileName) {
        FileOutputStream fos = null;
        ObjectOutputStream oos = null;

        try {
            fos = context.openFileOutput(cacheFileName, Context.MODE_PRIVATE);
            oos = new ObjectOutputStream(fos);
            oos.writeObject(ser);
            oos.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                oos.close();
            } catch (Exception ignored) {
            }
            try {
                fos.close();
            } catch (Exception ignored) {
            }
        }
    }

    public boolean isExistDataCache(String cacheFileName) {
        File data = context.getFileStreamPath(cacheFileName);
        return data.exists();
    }

    public Serializable readDataCache(String cacheFileName) {
        if (!isExistDataCache(cacheFileName))
            return null;

        FileInputStream fis = null;
        ObjectInputStream ois = null;

        try {
            fis = context.openFileInput(cacheFileName);
            ois = new ObjectInputStream(fis);
            return (Serializable) ois.readObject();
        } catch (FileNotFoundException ignored) {
        } catch (Exception e) {
            e.printStackTrace();
            if (e instanceof InvalidClassException) {
                File data = context.getFileStreamPath(cacheFileName);
                data.delete();
            }
        } finally {
            try {
                ois.close();
            } catch (Exception ignored) {
            }
            try {
                fis.close();
            } catch (Exception ignored) {
            }
        }
        return null;
    }

    public void deleteDataCache(String cacheFileName) {
        File data = context.getFileStreamPath(cacheFileName);
        if (data.exists()) {
            data.delete();
        }
    }
}
